{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w5_pa5kKPzAE"
      },
      "source": [
        "# Message Cookbook"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1tGC1kVjPNX9"
      },
      "source": [
        "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1qyi4bnAbnYink-FKaAlJG9OipyEWXEsT?usp=sharing).\n",
        "\n",
        "<div class=\"align-center\">\n",
        "  <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\"width=\"150\"></a>\n",
        "  <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\"  width=\"150\"></a></a>\n",
        "  \n",
        "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)\n",
        "</div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This notebook demonstrates how to set up and leverage CAMEL's ability to use `BaseMessage` class.\n",
        "\n",
        "In this notebook, you'll explore:\n",
        "\n",
        "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",
        "\n",
        "* **BaseMessage**: The base class for message objects used in the CAMEL chat system. It is designed to provide a consistent structure for the messages in the system and allow for easy conversion between different message types."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OnmoAw2vQG8I"
      },
      "source": [
        "In this tutorial, we will explore the `BaseMessage` class. The topics covered include:\n",
        "\n",
        "1. Introduction to the `BaseMessage` class.\n",
        "2. Creating a `BaseMessage` instance.\n",
        "3. Understanding the properties of the `BaseMessage` class.\n",
        "4. Using the methods of the `BaseMessage` class.\n",
        "5. Give message to `ChatAgent`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kETDiaP2Rrdb"
      },
      "source": [
        "## 📦 Installation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Cg96MkbcRtQR"
      },
      "source": [
        "First, install the CAMEL package with all its dependencies:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZVmDAK6MPefC"
      },
      "outputs": [],
      "source": [
        "!pip install \"camel-ai==0.2.16\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MyTTCe3IR_Lr"
      },
      "source": [
        "## 🔑 Setting Up API Keys"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "REqzgGL9SEaD"
      },
      "source": [
        "You'll need to set up your API keys for OpenAI. This ensures that the tools can interact with external services securely."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "PNBFEXc-R-0s",
        "outputId": "3efcae2c-a001-4098-a78f-bb8fb611925f"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from getpass import getpass\n",
        "\n",
        "# Prompt for the API key securely\n",
        "openai_api_key = getpass('Enter your API key: ')\n",
        "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [],
      "source": [
        "import os\n",
        "from getpass import getpass\n",
        "\n",
        "# Prompt for the AgentOps API key securely\n",
        "agentops_api_key = getpass('Enter your API key: ')\n",
        "os.environ[\"AGENTOPS_API_KEY\"] = agentops_api_key"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Your can go to [here](https://console.mistral.ai/api-keys/) to get API Key from Mistral AI with **free** credits."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Prompt for the API key securely\n",
        "mistral_api_key = getpass('Enter your API key: ')\n",
        "os.environ[\"MISTRAL_API_KEY\"] = mistral_api_key"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_9RKJHGBXvfd"
      },
      "source": [
        "## Give message to `ChatAgent` directly\n",
        "You can simply pass text message to `ChatAgent`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DKcOX661Xvfd",
        "outputId": "aacee56c-7f1e-4220-d98d-f08baeaabb0d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, CAMEL AI! It's great to connect with a community dedicated to the study of autonomous and communicative agents. Your work in this fascinating field is important for advancing our understanding of AI and its applications. How can I assist you today?\n"
          ]
        }
      ],
      "source": [
        "from camel.agents import ChatAgent\n",
        "\n",
        "# Define system message\n",
        "sys_msg = \"You are a helpful assistant.\"\n",
        "\n",
        "# Set agent\n",
        "camel_agent = ChatAgent(system_message=sys_msg)\n",
        "\n",
        "# Set user message\n",
        "user_msg = \"\"\"Say hi to CAMEL AI, one open-source community dedicated to the\n",
        "    study of autonomous and communicative agents.\"\"\"\n",
        "\n",
        "# Get response information\n",
        "response = camel_agent.step(user_msg)\n",
        "print(response.msgs[0].content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "X5scuZsGYGS9"
      },
      "source": [
        "## Give message to `ChatAgent` via `BaseMessage`\n",
        "\n",
        "For more complex message usage like multi-modal message, we suggest using `BaseMessage`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LRojeqp7dP1m"
      },
      "source": [
        "### Creating a `BaseMessage` Instance"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_sJV9GFldTBh"
      },
      "source": [
        "To create a `BaseMessage` instance, you need to provide the following arguments:\n",
        "\n",
        "- `role_name`: The name of the user or assistant role.\n",
        "- `role_type`: The type of role, either `RoleType.ASSISTANT` or `RoleType.USER`.\n",
        "- `content`: The content of the message.\n",
        "- `meta_dict`: An metadata dictionary for the message.\n",
        "\n",
        "Below are optional arguments you can pass:\n",
        "\n",
        "- `video_bytes`: Optional bytes of a video associated with the message.\n",
        "- `image_list`: Optional list of PIL Image objects associated with the message.\n",
        "- `image_detail`: Detail level of the images associated with the message. Default is \"auto\".\n",
        "- `video_detail`: Detail level of the videos associated with the message. Default is \"low\".\n",
        "\n",
        "Here's an example of creating a `BaseMessage` instance:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "pAdDeN7DdUgr"
      },
      "outputs": [],
      "source": [
        "from camel.messages import BaseMessage\n",
        "from camel.types import RoleType\n",
        "\n",
        "message = BaseMessage(\n",
        "    role_name=\"test_user\",\n",
        "    role_type=RoleType.USER,\n",
        "    content=\"test content\",\n",
        "    meta_dict={}\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MBx8Pje9ETAL"
      },
      "source": [
        "Additionally, the BaseMessage class provides class methods to easily create user and assistant agent messages:\n",
        "\n",
        "1. Creating a user agent message:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "pEiFYV-yez5j"
      },
      "outputs": [],
      "source": [
        "from camel.messages import BaseMessage\n",
        "\n",
        "user_message = BaseMessage.make_user_message(\n",
        "    role_name=\"user_name\",\n",
        "    content=\"test content for user\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PCqjf_fWEdLD"
      },
      "source": [
        "2. Creating an assistant agent message:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "id": "iIWWSfSpEf2n"
      },
      "outputs": [],
      "source": [
        "from camel.messages import BaseMessage\n",
        "\n",
        "assistant_message = BaseMessage.make_assistant_message(\n",
        "    role_name=\"assistant_name\",\n",
        "    content=\"test content for assistant\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yR5ZYr5yEkLL"
      },
      "source": [
        "## Using the Methods of the `BaseMessage` Class"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Gfc6WNUOEktw"
      },
      "source": [
        "The `BaseMessage` class offers several methods:\n",
        "\n",
        "1. Creating a new instance with updated content:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "P7UjCsb-Emsk",
        "outputId": "077116bd-3b9f-4fe0-e605-1d2b8814eaa1"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "new_message = message.create_new_instance(\"new test content\")\n",
        "print(isinstance(new_message, BaseMessage))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "412MphuYErw_"
      },
      "source": [
        "2. Converting to an `OpenAIMessage` object:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "sS_UKtJGEsPE",
        "outputId": "bb7c150e-cbd7-42c2-b2c2-caf9180ce037"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "from camel.types import OpenAIBackendRole\n",
        "openai_message = message.to_openai_message(role_at_backend=OpenAIBackendRole.USER)\n",
        "print(openai_message == {\"role\": \"user\", \"content\": \"test content\"})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TIpjz3G2E5dy"
      },
      "source": [
        "3. Converting to an `OpenAISystemMessage` object:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Ur4u2HdIE5ua",
        "outputId": "9713ccbf-d59c-4853-f889-6fbd80ca332b"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "openai_system_message = message.to_openai_system_message()\n",
        "print(openai_system_message == {\"role\": \"system\", \"content\": \"test content\"})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "523x8XqLE8Qo"
      },
      "source": [
        "4. Converting to an `OpenAIUserMessage` object:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mRCa7soNE9um",
        "outputId": "a140ffa4-fa5c-406c-b25c-d980ba95a6dc"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "openai_user_message = message.to_openai_user_message()\n",
        "print(openai_user_message == {\"role\": \"user\", \"content\": \"test content\"})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TURczNJNFA3J"
      },
      "source": [
        "5. Converting to an `OpenAIAssistantMessage` object:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5FnnmlRuFCtW",
        "outputId": "5748029e-e87d-4872-b859-798bfb68f3b8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "openai_assistant_message = message.to_openai_assistant_message()\n",
        "print(openai_assistant_message == {\"role\": \"assistant\", \"content\": \"test content\"})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eRhObgkxFFUi"
      },
      "source": [
        "6. Converting to a dictionary:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OQouave-FG15",
        "outputId": "e6c75309-98dd-45b7-dcd4-31ad79ba4ccf"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n"
          ]
        }
      ],
      "source": [
        "message_dict = message.to_dict()\n",
        "print(message_dict == {\n",
        "    \"role_name\": \"test_user\",\n",
        "    \"role_type\": \"USER\",\n",
        "    \"content\": \"test content\"\n",
        "})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "seSeG3KAHbLI"
      },
      "source": [
        "These methods allow you to convert a `BaseMessage` instance into different message types depending on your needs."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kAyagBo0GusE"
      },
      "source": [
        "## Give `BaseMessage` to `ChatAgent`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "nbr7nIKxGz07",
        "outputId": "18d99774-b808-4f59-bca4-37606e075ed3"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The image features a logo for \"CAMEL-AI.\" It includes a stylized depiction of a camel to the left, followed by the text \"CAMEL-AI\" in a bold, purple font.\n"
          ]
        }
      ],
      "source": [
        "from io import BytesIO\n",
        "\n",
        "import requests\n",
        "from PIL import Image\n",
        "\n",
        "from camel.agents import ChatAgent\n",
        "from camel.messages import BaseMessage\n",
        "# URL of the image\n",
        "url = \"https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png\"\n",
        "response = requests.get(url)\n",
        "img = Image.open(BytesIO(response.content))\n",
        "\n",
        "# Define system message\n",
        "sys_msg = BaseMessage.make_assistant_message(\n",
        "    role_name=\"Assistant\",\n",
        "    content=\"You are a helpful assistant.\",\n",
        ")\n",
        "\n",
        "# Set agent\n",
        "camel_agent = ChatAgent(system_message=sys_msg)\n",
        "\n",
        "# Set user message\n",
        "user_msg = BaseMessage.make_user_message(\n",
        "    role_name=\"User\", content=\"\"\"what's in the image?\"\"\", image_list=[img]\n",
        ")\n",
        "\n",
        "# Get response information\n",
        "response = camel_agent.step(user_msg)\n",
        "print(response.msgs[0].content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 🌟 Highlights"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This notebook has guided you through setting up and converting `BaseMessage` to different types of messages. These components play essential roles in the CAMEL chat system, facilitating the creation, management, and interpretation of messages with clarity.\n",
        "\n",
        "Key tools utilized in this notebook include:\n",
        "\n",
        "*   **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",
        "*   **BaseMessage**: The base class for message objects used in the CAMEL chat system. It is designed to provide a consistent structure for the messages in the system and allow for easy conversion between different message types.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "That's everything: Got questions about 🐫 CAMEL-AI? Join us on [Discord](https://discord.camel-ai.org)! Whether you want to share feedback, explore the latest in multi-agent systems, get support, or connect with others on exciting projects, we’d love to have you in the community! 🤝\n",
        "\n",
        "Check out some of our other work:\n",
        "\n",
        "1. 🐫 Creating Your First CAMEL Agent [free Colab](https://docs.camel-ai.org/cookbooks/create_your_first_agent.html)\n",
        "\n",
        "2.  Graph RAG Cookbook [free Colab](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)\n",
        "\n",
        "3. 🧑‍⚖️ Create A Hackathon Judge Committee with Workforce [free Colab](https://colab.research.google.com/drive/18ajYUMfwDx3WyrjHow3EvUMpKQDcrLtr?usp=sharing)\n",
        "\n",
        "4. 🔥 3 ways to ingest data from websites with Firecrawl & CAMEL [free Colab](https://colab.research.google.com/drive/1lOmM3VmgR1hLwDKdeLGFve_75RFW0R9I?usp=sharing)\n",
        "\n",
        "5. 🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth [free Colab](https://colab.research.google.com/drive/1lYgArBw7ARVPSpdwgKLYnp_NEXiNDOd-?usp=sharingg)\n",
        "\n",
        "Thanks from everyone at 🐫 CAMEL-AI\n",
        "\n",
        "\n",
        "<div class=\"align-center\">\n",
        "  <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\"width=\"150\"></a>\n",
        "  <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\"  width=\"150\"></a></a>\n",
        "  \n",
        "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)\n",
        "</div>\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python (case study)",
      "language": "python",
      "name": "case_study"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.16"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
